const UserModel = require('../model/user')
const SubmitWorkModel = require('../model/submitWork')
const tookit = require('../common/index')
const createToken = tookit.createToken
const sha1 = tookit.createHash
const verifyToken = tookit.verifyToken
const path = require('path')
const fs = require("fs")


const register = async function (ctx, next) {
    let res;
    try {
        let personEntity = new UserModel(ctx.request.body);
        personEntity.pwd = sha1(personEntity.pwd);
        res = await personEntity.save();
    } catch (err) {
        if (err.toString().indexOf('email_') > 1) {
            console.log('email 已经存在了');
            ctx.body = 'email already exists'
        } else if (err.toString().indexOf('code_') > 1) {
            console.log('code 已经存在了');
            ctx.body = 'code already exists'
        }
        return
    }
    ctx.body = res;
}

const get = async function (ctx, next) {
    let res = await UserModel.find(ctx.query);
    ctx.body = {
        data: res,
        status: 'ok'
    }
}

const update = async function (ctx, next) {
    try {
        let id = ctx.request.body._id;
        {
            let res = await UserModel.find({_id: id});//可能是一个数组
            if (!res) {
                ctx.body = {
                    status: 'fail',
                    fail: 'code is not exists'
                }
                return
            }
        }
        let update = ctx.request.body; //let update = {$set : ctx.request.body};//日后如果要只修改部分
        update.pwd = sha1(update.pwd)
        let res = await UserModel.updateOne({_id: id}, update);
        ctx.body = res
    } catch (err) {
        if (err.toString().indexOf('email_') > 1) {
            console.log('email 已经存在了');
            ctx.body = 'email already exists'
        } else if (err.toString().indexOf('code_') > 1) {
            console.log('code 已经存在了');
            ctx.body = 'code already exists'
        }
        return
    }
}

const login = async function (ctx, next) {
    console.log(ctx);
    console.log(ctx.request.body.pwd);
    ctx.request.body.pwd = sha1(ctx.request.body.pwd)
    let res = (await UserModel.find(ctx.request.body))[0];
    console.log(res);
    if (!res) {
        ctx.body = {
            status: 'fail',
            fail: 'code is not exists or password is false'
        }
        return
    }
    let token = createToken({code: res.code});
    res.token = token;
    await res.save();
    // ctx.session.token = res.token;
    // ctx.session.code = res.code;
    ctx.body = {
        data: res,
    }
}
const DelUser = async (ctx, next) => {
    //拿到要删除的用户id
   try{
       let id = ctx.request.body._id;
       var res = await UserModel.findOneAndRemove({_id: id});
       ctx.status = 200;
       ctx.body = {
           status: res
       };
   }catch(err){
       ctx.body = err;
   }
};

const  updateById = async function (ctx, next) {
    try {
        let result = await UserModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new : true}).exec();
        return ctx.body = { status : 'ok', data : result};
    } catch (e) {
        return ctx.body = { status : 'fail', data : e.message};
    }
}


const logout = async (ctx, next) => {
    try {
        //获取用户的id
        let id = ctx.request.body._id;
        console.log(id);
        // 通过authorization请求头获取token
        let token = (ctx.request.headers)['authorization'];
        // 如果token不存在
        if (!token) {
            ctx.body = {status: 'fail', data: 'token no found'};
            return
        }
        // 获取验证token后的数据
        let result = verifyToken(token);
        // token验证失败
        if (result == false) {
            // 响应401和token过期
            ctx.status = 401;
            return ctx.body = {status: 'fail', data: 'token过期'};
        }

        let nModified = await UserModel.updateOne({_id: id}, {$set: {token: ''}})
        // 删除数据库的token响应登出信息
        return ctx.body = {
            status: 'ok',
            data: nModified.nModified != 0 ? '登出成功' : '您已经登出',
        }
    } catch (e) {
        return ctx.body = {status: 'fail', data: e.message,}
    }
}

const excel = async (address) => {
    if (typeof require !== 'undefined') XLSX = require('xlsx');
    let workbook = XLSX.readFile(address);
    let sheet_name_list = workbook.SheetNames;
    /*处理表格*/
    let arr = []
    sheet_name_list.forEach(function (sheetname) { /* iterate through sheets */
        var worksheet = workbook.Sheets[sheetname];
        console.log(worksheet.length);
        for (z in worksheet) {
            if (z[0] === '!') continue;
            console.log(sheetname + ": " + z + "=" + JSON.stringify(worksheet[z].v));
            if (!z.indexOf('A')) {
                var code = (worksheet[z].v).toString();
            }
            if (!z.indexOf('B')) {
                var pwd = (worksheet[z].v).toString();
            }
            if (!z.indexOf('C')) {
                var name = (worksheet[z].v).toString();
            }
            if (!z.indexOf('D')) {
                var power = (worksheet[z].v).toString();
            }
            if (!z.indexOf('E')) {
                var className = (worksheet[z].v).toString();
                // arr.push({'code': code, 'pwd': pwd,'name':name,'power':power,'className':className})
            }
            if (!z.indexOf('F')) {
                var lassCode = (worksheet[z].v).toString();
                arr.push({'code': code, 'pwd': pwd,'name':name,'power':power,'className':className,'lassCode':lassCode})
            }
        }
    });
    return (arr);
}

const importPeople = async function (ctx, next) {
    let address = ctx.params.address
    let arrPeople = await excel('./excel/'+address)
    try {
        for (let i = 0; i < arrPeople.length; i++) {
            let personEntity = new UserModel(arrPeople[i])
            personEntity.pwd = sha1(personEntity.pwd);
            await personEntity.save();
        }
        ctx.body = arrPeople
    } catch (err) {
        ctx.body = err
    }


}

const uploadfile = async function (ctx, next) {
    let formidable = require('formidable');
    let form = new formidable.IncomingForm();
    form.uploadDir = path.normalize(__dirname + "/../excel");
    var flag = await new Promise((resolve, reject) => {
        form.parse(ctx.req, function (err, fields, files) {
            let oldpath = files.upload.path;
            let newpath = path.resolve(__dirname + "/../excel", files.upload.name);
            fs.rename(oldpath, newpath, function (err) {
                if (err) {
                    return reject('fail');
                    ctx.body = "上传失败";
                    return;
                }
            });
            return resolve('ok');
        })
    })
    ctx.body={
        status:flag
    }

}

// const submit = async function (ctx, next) {
//     let res;
//     try {
//         let personEntity = new SubmitWorkModel(ctx.request.body);
//         //personEntity.pwd = sha1(personEntity.pwd);
//         res = await personEntity.save();
//     } catch (err) {
//         console.log('err====',err);
//         return
//     }
//     ctx.body = res;
// }

// const getWorkData = async function (ctx, next) {
//     //console.log(ctx)
//     let res = await SubmitWorkModel.find(ctx.title);
//     console.log(res)
//     ctx.body = {
//         data: res,
//         status: 'ok'
//     }
// }


module.exports = {
    register,
    login,
    get,
    update,
    DelUser,
    logout,
    importPeople,
    uploadfile,
    updateById
    // submit,
    // getWorkData
};